/////////////////////////////////////////////
// ObjectARX defined commands

#include "StdAfx.h"
#include "StdArx.h"


// This is command 'PKBLK'
void pkblk()
{
	ads_name ent;
	ads_point pickPt;
	AcDbObjectId entId;
	AcDbObjectId blkDefId;
	AcDbObjectId attId;
	AcDbEntity *pEnt;
	AcDbBlockReference *pBlkRef;
	AcDbBlockTableRecord *pBlkDefRecord;
	AcDbAttributeDefinition *pAttDef;
	AcDbObjectIterator *pAttItr;
	AcDbAttribute *pAtt;
	char* pTagPrompt;
	char* pValue;
	char tagValue[255];
	char promptValue[255];
	char attStrValue[255];
	char kw[4];

	int retCode;

	retCode = acedEntSel("\nSelect Block reference. ", ent, pickPt);
	switch(retCode)
	{
		case RTERROR :
			acutPrintf("\nNothing selected!! ");
			return;
		break;

		case RTCAN :
			acutPrintf("\nUser canceled. ");
			return;
		break;
	}

	// Get the ObjectId of the selected entity
	acdbGetObjectId(entId, ent);

	acdbOpenAcDbEntity(pEnt, entId, AcDb::kForRead);

	pBlkRef = AcDbBlockReference::cast(pEnt);

	if(pBlkRef == NULL)
	{
		acutPrintf("\nNot a block reference. ");
		pEnt->close();
		return;
	}
	
	blkDefId = pBlkRef->blockTableRecord();

	acdbOpenObject(pBlkDefRecord, blkDefId, AcDb::kForRead);

	if(!pBlkDefRecord->hasAttributeDefinitions())
	{
		acutPrintf("\nThe selected block has no attributes. ");
		pBlkDefRecord->close();
		pEnt->close();
		return;
	}

	pAttItr = pBlkRef->attributeIterator();
	for(pAttItr->start(); !pAttItr->done(); pAttItr->step())
	{
		attId = pAttItr->objectId();
		pBlkRef->openAttribute(pAtt, attId, AcDb::kForRead);
		pTagPrompt = pAtt->tag();
		strcpy(tagValue, pTagPrompt);
		pAttDef = getAttDef(tagValue, pBlkDefRecord);
		free(pTagPrompt);
		if(pAttDef == NULL)
		{
			pAtt->close();
			break;
		}
		pTagPrompt = pAttDef->prompt();
		strcpy(promptValue, pTagPrompt);
		free(pTagPrompt);
		pValue = pAtt->textString();
		strcpy(attStrValue, pValue);
		free(pValue);

		acutPrintf("%s%s%s%s", "\n", promptValue, " = \"", attStrValue);

		acedInitGet(NULL, "Yes No");
		retCode = acedGetKword("\" - Change [Yes/No]<No>: ", kw);

		switch(retCode)
		{
			case RTERROR :
				acutPrintf("\nError in acedGetKword ");
			break;

			case RTCAN :
				acutPrintf("\nUser canceled. ");
			break;

			case RTNONE:
				strcpy(kw, "No");
				retCode = RTNORM;
			break;
		}

		if(strcmp(kw, "Yes") == 0)
		{
			acedGetString(1, "\nNew value: ", attStrValue);
			pAtt->upgradeOpen();	// Dont forget to upgrade it first!!
			pAtt->setTextString(attStrValue);
		}

		pAtt->close();
	}

	delete pAttItr;

	pBlkDefRecord->close();
	
	pEnt->close();
}

